package android07.newtop.adapter;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.Log;
import android.view.ViewGroup;


import java.util.HashMap;

import android07.newtop.R;
import android07.newtop.fragment.MainFragment;


/**
 * 首页MainActivity的viewpager的 适配器，和listview的适配器类似
 * 主要用来管理fragment页面
 */
public class MyPagerAdapter extends FragmentPagerAdapter {

    private static final String TAG = "MyPagerAdapter";
    //将首页的的几个fragment 存起来到内存中，这样能迅速调用
    private HashMap<String, Fragment> fragments;

    //标题集
    private String[] tabs ;

    private String[] tabvalue ;
    //这个是上下文
    Context context;


    public MyPagerAdapter(Context context, FragmentManager fm) {
        super(fm);
        this.context = context;
        tabs=context.getResources().getStringArray(R.array.tab);
        tabvalue=context.getResources().getStringArray(R.array.tabvalue);
        fragments = new HashMap<String, Fragment>();
    }

    /**
     * 切换fragment的时候调用此方法
     * @param position
     * @return
     */
    @Override
    public Fragment getItem(int position) {
        Log.d(TAG, "getItem: position="+position);
        Fragment fragment;

        fragment = new MainFragment();
        Bundle bundle0 = new Bundle();
        bundle0.putString("tabvalue", tabvalue[position]);
        fragment.setArguments(bundle0);

        fragments.put(position + "", fragment);
        return fragment;
    }

    @Override
    public int getCount() {

        Log.d(TAG, "getCount: tabs.length+"+tabs.length);
        return tabs.length;

    }

    @Override
    public CharSequence getPageTitle(int position) {
        Log.d(TAG, "getPageTitle: ");
        return tabs[position];
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        super.destroyItem(container, position, object);
        Log.d(TAG, "destroyItem: ");
        fragments.remove(position);

    }


    /**
     * 通过position获取map中的Fragment实例
     * @param position
     * @return
     */
    public Fragment getFragment(int position) {
        return fragments.get(position + "");
    }
}
